package oop.core.view;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JList;
import javax.swing.JPopupMenu;

import oop.core.med.LevelUpMediator;
import oop.core.skill.ActiveSkill;
import oop.core.skill.InteractiveSkill;
import oop.core.skill.PassiveSkill;

/**
 * This is the menu that pops up to allow the user to select which skills to level up.
 * 
 * @author Stephanie
 *
 */

public class LevelUpPopupMenu extends JPopupMenu implements ActionListener {

	private List<InteractiveSkill> interactive;
	private List<PassiveSkill> passive;
	private List<ActiveSkill> active;
	private LevelUpMediator levelUpMediator;
	private JButton[] buttons;
	private int points;
	
	
	/**
	 * Contsructor takes a levelupMediator. Gets Skill lists from there.
	 * Creates an array of buttons to allows for a variable number of skills.
	 * Points are the number of points given to the user to distribute
	 * upon every level up. 
	 * @param levelUpMediator
	 */
	public LevelUpPopupMenu( LevelUpMediator levelUpMediator ) {
		this.levelUpMediator = levelUpMediator;
		this.interactive = levelUpMediator.getInteractive();
		this.passive = levelUpMediator.getPassive();
		this.active = levelUpMediator.getActive();
		buttons = new JButton[30];
		points = 5;
		initialize();
	}
	
	/**
	 * When a button is pressed, this method matches its name
	 * to gets its name and sends it to the LevelUpMediator.
	 * After 5 clicks, this window closes.
	 */
	@Override
	public void actionPerformed(ActionEvent e) {
		if ( points == 0 )
			hide();
		else {
			JButton button = (JButton) e.getSource();
			for ( int i = 0; i < buttons.length; i++ ) {
				if ( buttons[i] != null ) {
					if ( buttons[i].equals(button)) {
						levelUpMediator.levelUp(buttons[i].getText());
						points--;
						System.out.println( points );
					}
				}
			}
		}
		
	}
	/**
	 * Part of the constructor. Initializes the buttons.
	 */
	private void initialize()
	{
		int index = 0;
		Iterator<InteractiveSkill> interactiveIter = interactive.iterator();
		Iterator<PassiveSkill> passiveIter = passive.iterator();
		Iterator<ActiveSkill> activeIter = active.iterator();
		while ( interactiveIter.hasNext() ) {
			InteractiveSkill is = interactiveIter.next();
			buttons[index++] = new JButton(is.getName());
		}
		while ( passiveIter.hasNext() ) {
			PassiveSkill ps = passiveIter.next();
			buttons[index++] = new JButton(ps.getName());
		}
		while ( activeIter.hasNext() ) {
			ActiveSkill as = activeIter.next();
			buttons[index++] = new JButton(as.getName());
		}
		
		for ( int i = 0; i < buttons.length; i++ ) {
			if ( buttons[i] != null) {
				buttons[i].addActionListener(this);
				add(buttons[i]);
			}
			
		}
	}

}
